package phone.book;

import java.io.InputStream;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class contacts extends ListActivity{

	ArrayList<Long> idlist;
	ArrayList<String> nlist;
	ArrayList<String> elist;
	ArrayList<Bitmap> imglist;
	AlertDialog.Builder alert;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        
        refresh_contacts();
  	
    }
    
	
	private void refresh_contacts() {
		imglist = new ArrayList<Bitmap>();
		nlist = new ArrayList<String>();
		idlist = new ArrayList<Long>();
		elist = new ArrayList<String>();
		ContentResolver cr = getContentResolver();
		
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,    null, null, null, null);
        
        if (cur.getCount() > 0) {
	        
        	while (cur.moveToNext()) {
        	Long id = Long.parseLong(cur.getString(cur.getColumnIndex(BaseColumns._ID)));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));           
            nlist.add(name);
            idlist.add(id);
         //   String mail = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
         //   elist.add(mail);
            Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
			
		    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
		    if (input == null) {
		        imglist.add( null);
		       // iv.setImageBitmap(null);
		       // iv.setImageResource(R.drawable.dialer);
		    }
		    else
		    {
		    	imglist.add(BitmapFactory.decodeStream(input));				    	
		    	//iv.setImageBitmap(BitmapFactory.decodeStream(input));
		    	//iv.setImageResource(R.drawable.dialer);
		    }
        	}
        	
        }
        setListAdapter(new MyAdaptor(this, android.R.layout.simple_list_item_1,R.id.text, nlist));
        
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inf = getMenuInflater();
		inf.inflate(R.layout.contactsmenu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
			case R.id.addContact: addContact();return true;
			case R.id.cimport: cimport();return true;
			case R.id.all_delete: all_delete();return true;
			default:return super.onOptionsItemSelected(item);
		}
	}
	
	private void all_delete() {
		ContentResolver cr = getContentResolver();
		
		//cr.query(uri, projection, selection, selectionArgs, sortOrder)
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
		while (cur.moveToNext()) { 
			try{ 
				String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
				
				Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
				System.out.println("The uri is " + uri.toString());
				cr.delete(uri, null, null);
				Intent i=new Intent(getApplicationContext(),PhonebookActivity.class);
				startActivityForResult(i, 0);
				}
			catch(Exception e){
				System.out.println(e.getStackTrace());
				}
			} 
	}


	private void cimport() {

		Intent i=new Intent(getApplicationContext(),log_in.class);
		startActivityForResult(i, 0);
	}


	private void addContact() {
		Intent i=new Intent(getApplicationContext(),Add_contact.class);
		startActivityForResult(i, 0);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i=new Intent(getApplicationContext(),contactDetails.class);
		long temp = idlist.get((int) id);
		i.putExtra("contactId", temp);		
		startActivityForResult(i, 0);
				
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		refresh_contacts();
	}
	
    private class MyAdaptor extends ArrayAdapter<String>{

		public MyAdaptor(Context context, int resource, int textViewResourceId,
				ArrayList<String> nlist) {
			super(context, resource, textViewResourceId, nlist);
			// TODO Auto-generated constructor stub
		}
    	
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View row = inflater.inflate(R.layout.contact, parent, false);
			//ContentResolver cr = getContentResolver();
			//Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,    null, null, null, null);
		       // TextView textview = new TextView(this); 
		        
		        
			    ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
			    TextView tv = (TextView) row.findViewById(R.id.text);
		        Log.d("id",Long.toString(idlist.get(position)));
	 			tv.setText(nlist.get(position));
				iv.setImageResource(R.drawable.contacts);
			/*	row.findViewById(R.id.text).setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v) {
						Intent i=new Intent(getApplicationContext(),contactDetails.class);
						int id = R.id.text;					
						i.putExtra("contactId", id);	
						startActivity(i);
					}
					
				});*/
				

		   
			return row;
		}
    }
    
}
